package org.apache.james;

import org.apache.james.mapper.CustomUserMapper;
import org.apache.james.model.CustomUser;
import org.apache.james.user.api.UsersRepositoryException;
import org.apache.james.user.api.model.User;
import org.apache.james.user.lib.AbstractUsersRepository;

import javax.inject.Inject;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * 用户库
 * @author ccoke
 */
public class CustomUserRepository extends AbstractUsersRepository {
    private final CustomUserMapper customUserMapper;

    @Inject
    public CustomUserRepository(CustomUserMapper customUserMapper) {
        this.customUserMapper = customUserMapper;
    }

    @Override
    public User getUserByName(String name) throws UsersRepositoryException {
        CustomUser customUser = customUserMapper.selectByName(name);
        return customUser;
    }

    @Override
    public boolean contains(String name) throws UsersRepositoryException {
        return customUserMapper.selectCountByName(name) != 0;
    }

    @Override
    public boolean test(String name, String password) throws UsersRepositoryException {
        CustomUser customUser = customUserMapper.selectByName(name);
        return Optional.ofNullable(customUser).map(CustomUser::getPassword).map(pass -> pass.equals(password)).orElse(false);
    }

    @Override
    public int countUsers() throws UsersRepositoryException {
        return customUserMapper.selectCount();
    }

    @Override
    public Iterator<String> list() throws UsersRepositoryException {
        List<String> users = customUserMapper.selectAll();
        return users.iterator();
    }

    @Override
    protected void doAddUser(String username, String password) throws UsersRepositoryException {
        // 不实现
    }

    @Override
    public void updateUser(User user) throws UsersRepositoryException {
        // 不实现
    }

    @Override
    public void removeUser(String name) throws UsersRepositoryException {
        // 不实现
    }
}
